package com.rem.concurrency.multithreading.syn;

import lombok.SneakyThrows;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 显示创建锁
 *
 * @author Rem
 * @date 2021-03-05
 */

public class SafeLock {

    public static void main(String[] args) {
        TestLock testLock = new TestLock();

        new Thread(testLock, "test1").start();
        new Thread(testLock, "test2").start();
        new Thread(testLock, "test3").start();
    }
}


class TestLock implements Runnable {

    private static Integer ticket = 10;
    //定义Lock锁
    private final ReentrantLock lock = new ReentrantLock();

    @SneakyThrows
    @Override
    public void run() {
        lock.lock();
        try {
            while (ticket > 0) {
                Thread.sleep(100);
                System.err.println(Thread.currentThread().getName() + "----" + ticket--);
            }
        } finally {
            lock.unlock();
        }
    }
}
